package com.wqj.ride.happyriding.location;

import android.content.Context;
import android.location.LocationManager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

public class MyLocationManager {
    private static MyLocationManager mInstance;

    private Context mContext;
    private AMapLocationClient mLocationClient;
    private AMapLocationListener mLocationListener;
    private OnLocationListener mListener;

    public MyLocationManager(Context ctx) {
        init(ctx);
    }

    private void init(Context ctx) {
        mContext = ctx;
        mLocationClient = new AMapLocationClient(ctx);
        mLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                mLocationClient.stopLocation();
                mListener.onLocationUpdate(aMapLocation);
            }
        };
        mLocationClient.setLocationListener(mLocationListener);
    }

    public static MyLocationManager getInstance(Context ctx) {
        if (null == mInstance) {
            synchronized (MyLocationManager.class) {
                if (null == mInstance) {
                    mInstance = new MyLocationManager(ctx);
                }
            }
        }
        return mInstance;
    }

    /**
     * 强制帮用户打开GPS
     */
    public boolean isGPSEnabled() {
        LocationManager locationManager = (LocationManager) mContext
                                        .getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps && network) {
            return true;
        }
        return false;
    }

    public void getCurrentLocation(OnLocationListener listener) {
        mListener = listener;

        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocationLatest(true);

        mLocationClient.stopLocation();
        mLocationClient.startLocation();
    }
}
